package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * @author: wudong
 * @create: 2021-07-27 11:25
 **/
public class HostConfig extends BaseContainer implements Lifecycle,RequestHandler {
    private final String path;
    private ClassLoader classLoader;

    private Map<String,HttpServlet> servletMap = new HashMap<>();

    private Set<Map.Entry<Pattern, HttpServlet>> servlets;

    public HostConfig(String path) {
        this.path = path;
    }

    @Override
    public void init() throws Exception {
        this.classLoader = new WebAppClassLoader(this.path);
    }

    @Override
    public void start() throws Exception {
        File xml = new File(path,"web.xml");
        loadServlet(xml,classLoader);

        servlets = new HashSet<>();
        for (Map.Entry<String, HttpServlet> stringHttpServletEntry : servletMap.entrySet()) {
            Map.Entry<Pattern, HttpServlet> entry = new Map.Entry() {
                @Override
                public Pattern getKey() {
                    return Pattern.compile(stringHttpServletEntry.getKey());
                }

                @Override
                public HttpServlet getValue() {
                    return stringHttpServletEntry.getValue();
                }

                @Override
                public Object setValue(Object value) {
                    return null;
                }
            };

            servlets.add(entry);
        }
    }

    /**
     * 加载解析web.xml，初始化Servlet
     */
    private void loadServlet(File xml, ClassLoader classLoader) throws Exception {
        InputStream resourceAsStream = new FileInputStream(xml);
        SAXReader saxReader = new SAXReader();

        try {
            Document document = saxReader.read(resourceAsStream);
            Element rootElement = document.getRootElement();

            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            for (int i = 0; i < selectNodes.size(); i++) {
                Element element =  selectNodes.get(i);
                // <servlet-name>lagou</servlet-name>
                Element servletnameElement = (Element) element.selectSingleNode("servlet-name");
                String servletName = servletnameElement.getStringValue();
                // <servlet-class>LagouServlet</servlet-class>
                Element servletclassElement = (Element) element.selectSingleNode("servlet-class");
                String servletClass = servletclassElement.getStringValue();


                // 根据servlet-name的值找到url-pattern
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                // /lagou
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                HttpServlet servlet = (HttpServlet) classLoader.loadClass(servletClass).newInstance();
                servlet.init();
                servletMap.put(urlPattern, servlet);
            }

        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            resourceAsStream.close();
        }

    }

    public Map<String, HttpServlet> getServletMap() {
        return servletMap;
    }

    @Override
    public void invoke(Request request, Response response) throws Exception {
        String url = request.getUrl();

        for (Map.Entry<Pattern, HttpServlet> servlet : servlets) {
            Pattern pattern = servlet.getKey();
            if(pattern.matcher(url).matches()){
                servlet.getValue().service(request,response);
                return;
            }
        }
        response.output(HttpProtocolUtil.getHttpHeader404());
    }
}
